/*
 * Zirco Browser for Android
 * 
 * Copyright (C) 2010 J. Devauchelle and contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 3 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

package com.gogowan.agroenterprise.utils;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.Contacts;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.Contents;
import com.gogowan.agroenterprise.contorl.Base64;
import com.gogowan.agroenterprise.contorl.HTTPCommit;
import com.gogowan.agroenterprise.contorl.Enum.Temp;
import com.gogowan.agroenterprise.model.Message;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.zxing.BarcodeFormat;


/**
 * 这个类主要是为了和服务器通讯的接口类
 * @author ns
 *
 */
@SuppressWarnings("deprecation")
public class ICodeUtils {

	static String[] table=new String[]{
		"DATA_MATRIX", //DM码,i码的基础  0
		"QR_CODE", // QR码 1, URL,火车票，4G等
		"EAN_13",   //各种商品使用的条码 2
		"PDF417",  // 3, 国务院办公厅的标准
		"AZTEC", //4
		"UPC_E", //5
		"UPC_A",//6
		"EAN_8", //7
		"UPC_EAN_EXTENSION", //8
		"CODE_128",     //9
		"CODE_39",  //10
		"CODE_93", //11
		"CODABAR", //12
		"ITF", //13
		"RSS14" , //14
		"RSS_EXPANDED", //15
		"ERROR", //16,不能处理的条码
		};
	public final static String MYCARD="MYCARD";

	public final static String ENCODE_CONTENT="ENCODE_CONTENT";
	
	public final static String PROMOTION = "PROMOTION";

	public static final String[] METHODS_PROJECTION = { BaseColumns._ID, // 0
			Contacts.ContactMethodsColumns.KIND, // 1
			Contacts.ContactMethodsColumns.DATA, // 2
	};

	public static final int PHONES_NUMBER_COLUMN = 1;

	public static final String[] PHONES_PROJECTION = { BaseColumns._ID, // 0
			Contacts.PhonesColumns.NUMBER // 1
	};
	public static final int METHODS_KIND_COLUMN = 1;
	public static final int METHODS_DATA_COLUMN = 2;
	
	/**
	 * 安卓市场
	 */
	public static final int ANDROID_MARKET=0;
	/**
	 * 安智市场
	 */
	public static final int ANZHI_MARKET=1;
	/**
	 * 机锋市场
	 */
	public static final int GFAN_MARKET=2;
	/**
	 * 获取Mainifest的版本号
	 * @param context
	 * @return
	 */
	public static String getVersionName(Context context){
	    String version = "0.0.0";
	    PackageManager packageManager = context.getPackageManager();   
	    try {   
	        PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);   
	        version = packageInfo.versionName;
	    } catch (NameNotFoundException e) {   
	        //e.printStackTrace();
	    }   
	       
	    return version.trim();   
	}  

	/**
	 * 得到传递类型
	 * @param format
	 * @return 
	 */
	static public String formatToT(String format){
		int i = 0;
		for (; i < table.length; i++) {
			if(format.equals(table[i])){
				return Integer.toString(i);
			}
		}
		return "-1";//不能处理返回-1,基本不能处理到这里。
	}
	
	/**
	 * 判断是否是飞网i码,如果是DM就是i码。如果i码规则有变,则放到这里处理
	 * @param rawResult
	 * @return
	 */
	public static boolean isICode(String format,String content){
		String dm=BarcodeFormat.DATA_MATRIX.name();
		String qr=BarcodeFormat.QR_CODE.name();
		boolean isNum=isNumeric(content);
		
		if(isNum&&(format.equals(dm)||format.equals(qr))){
			return true;
		}
		else
		{
			return false;
		}
		//return format.equals(BarcodeFormat.DATA_MATRIX);		
	}
	
	/**
	 * 是否为数字
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		for (int i = 0;i < str.length();i++) {	
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}
	/**
	 * 得到服务器的URL地址
	 * @param format 格式
	 * @param code i码
	 * @param isPaima 是否是拍码
	 * @return url地址
	 */
	public static String getServerURL(String format, String code,boolean isPaima) {
		//先base64
		String result = "";
		try {
			byte[] b;
			b = Base64.encode(code.getBytes("UTF-8"), 0);
			result = new String(b, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			result = "";
		}
	 
		//再uri, 主要是为了处理base64中的中的=和+		
		try {
			result = URLEncoder.encode(result);// 不使用base64,使用uri
		} catch (Exception e) {
		}
		StringBuffer serverURL=new StringBuffer();
//		String serverURL = "http://mb.188114.net/dm.aspx?e=1&t=" + formatToT(format)
//				+ "&code=" + result;
		serverURL.append("http://mb.188114.net/dm.aspx?e=1");
		if(isPaima)
		{
			serverURL.append("&t=" + formatToT(format));
		}else
		{
			serverURL.append("&t=" + 16);//输码为16
		}
		serverURL.append("&code=" + result);
		return serverURL.toString();
	}
	public static String getServerURL(String format,String icode) {
		return getServerURL(format,icode,true);
	}
	 /**
	  * 得到服务器的URL地址
	 * @param code
	 * @return
	 */
//	public static String getICodeServerURL(String icode,boolean isPaima) {
//		return getServerURL(BarcodeFormat.DATA_MATRIX.toString(),icode,isPaima);
//	}
	
	
	/**
	 * 加密密码
	 */
	private final static String KEY = "12345678";
	/**
	 * 加密向量
	 */
	private final static String IV = "12345678";

	/**
	 * 商户采集类型
	 */
	public final static int SH_COLLECTION = 0;
	/**
	 * 住户采集类型
	 */
	public final static int ZH_COLLECTION = 1;
	/**
	 * 统计类型
	 */
	public final static int STATISTICS = 2;
	/**
	 * 核实任务类型
	 */
	public final static int HS_COLLECTION = 3;
	/**
	 * 服务器页面
	 */
	public final static String URLPAGE = "ServerHandler.ashx";
	
	/**
	 * 1-9转换成01-09
	 * 
	 * @param 数字
	 * @return 字符串
	 */
	public static String formatTime(int time) {

		String timeStr = "";
		if (time < 10) {
			timeStr = "0" + String.valueOf(time);
		} else {
			timeStr = String.valueOf(time);
		}
		return timeStr;
	}

	/**
	 * 2011-10-12转化成数组：[年，月，日]
	 * 
	 * @param 字符串
	 * @return 数组
	 */
	public static int[] forNums(String str) {
		String[] date = str.trim().split("-");
		int nums[] = new int[date.length];
		try {

			for (int i = 0; i < date.length; i++) {
				nums[i] = Integer.parseInt(date[i]);
			}
		} catch (Exception e) {

		}
		// Log.d("date-----------", ""+nums[0]+"-"+nums[1]+"-"+nums[2]);
		return nums;
	}

	/**
	 * 加密
	 * 
	 * @param 内容
	 * @return 加密后内容
	 */
	public static java.lang.String encrypt(String value) {
		byte[] key = null, iv = null;
		try {
			key = KEY.getBytes("utf-8");
			iv = IV.getBytes("utf-8");
		} catch (UnsupportedEncodingException e1) {

		}
		String result = null;
		byte[] tmpOriginalStr = null;
		try {
			if (!isEmpty(value)) {
				tmpOriginalStr = value.getBytes("utf-8");
				SecretKeyFactory keyFactory = SecretKeyFactory
						.getInstance("DES");
				DESKeySpec dks = new DESKeySpec(key);
				SecretKey secretKey = keyFactory.generateSecret(dks);
				IvParameterSpec param = new IvParameterSpec(iv);
				Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
				cipher.init(Cipher.ENCRYPT_MODE, secretKey, param);
				byte[] tmpEncypt = cipher.doFinal(tmpOriginalStr);
				if (tmpEncypt != null) {
					// BASE64Encoder bse=new BASE64Encoder();
					// result=bse.encode(tmpEncypt);
					byte[] b = Base64.encode(tmpEncypt, 0);
					result = new String(b, "utf-8");
				}
			}
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * 解密
	 * 
	 * @param 加密内容
	 * @return 解密后内容
	 */
	public static java.lang.String decrypt(String value) {
		byte[] key = null, iv = null;
		try {
			key = KEY.getBytes("utf-8");
			iv = IV.getBytes("utf-8");
		} catch (UnsupportedEncodingException e1) {

		}
		String result = null;
		byte[] tmpEncrypStr = null;
		try {
			if (!isEmpty(value)) {
				// BASE64Decoder bd=new BASE64Decoder();
				// tmpEncrypStr =bd.decodeBuffer(encrypStr);
				tmpEncrypStr = Base64.decode(value, 0);
				SecretKeyFactory keyFactory = SecretKeyFactory
						.getInstance("DES");
				DESKeySpec dks = new DESKeySpec(key);
				SecretKey secretKey = keyFactory.generateSecret(dks);
				IvParameterSpec param = new IvParameterSpec(iv);
				Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
				cipher.init(Cipher.DECRYPT_MODE, secretKey, param);
				byte[] tmpDecrypt = cipher.doFinal(tmpEncrypStr);
				if (tmpDecrypt != null) {
					result = new String(tmpDecrypt, "utf-8");
				}
			}
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * 字符串是否为空
	 * 
	 * @param 字符串
	 * @return 是或否
	 */
	public static boolean isEmpty(String str) {
		if (str == null) {
			return true;
		} else if (str.equals("") || str.equals("null")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 得到枚举值
	 * 
	 * @param str
	 * @return 枚举值
	 */
	public static int getTempValue(Temp str) {
		int id = 0;
		for (Temp t : Temp.values()) {
			/* 通过getValue()取得相关枚举的值 */
			// System.out.println(t+"的值是"+t.getValue());
			if (t.equals(str)) {
				id = t.getValue();
			}
		}
		return id;
	}

	/**
	 * json转换成对象
	 * 
	 * @param json字符串
	 * @param 对象类型
	 * @return 对象
	 */
	public static Object fromJSON(String jsonString, Type targetType) {
		Object object = null;
		GsonBuilder builder = new GsonBuilder();
		builder.serializeNulls();
		Gson gson = builder.create();
		object = gson.fromJson(jsonString, targetType);
		return object;
	}

	/**
	 * 对象转换成json
	 * 
	 * @param 对象
	 * @return json字符串
	 */
	public static String toJSON(Object objectVal) {
		GsonBuilder builder = new GsonBuilder();
		builder.serializeNulls();
		Gson gson = builder.create();
		return gson.toJson(objectVal);
	}


	/**
	 * 数据库更新
	 * 
	 * @param context
	 * @param id
	 * @param values
	 * @param table
	 */
	public static void update(Context context, String id, ContentValues values,
			String table) {
		try {
			// 创建一个DatabaseHelper对象
			DBHelper dbHelper = new DBHelper(context);
			// 得到一个可写的SQLiteDatabase对象
			SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase();
			// 创建一个ContentValues对象

			// 调用update方法
			// 第一个参数String：表名
			// 第二个参数ContentValues：ContentValues对象
			// 第三个参数String：where字句，相当于sql语句where后面的语句，？号是占位符
			// 第四个参数String[]：占位符的值
			sqliteDatabase.update(table, values, "id=?", new String[] { id });
			sqliteDatabase.close();
			dbHelper.close();
			// System.out.println("-----------update------------");
		} catch (SQLiteException e) {
			Log.d("e=", e.toString());
		}
	}

	/**
	 * 数据库添加
	 * 
	 * @param context
	 * @param values
	 * @param table
	 */
	public static void insert(Context context, ContentValues values,
			String table) {
		try {
			// 创建DatabaseHelper对象
			DBHelper dbHelper = new DBHelper(context);
			// 得到一个可写的SQLiteDatabase对象
			SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase();
			// 调用insert方法，就可以将数据插入到数据库当中
			// 第一个参数:表名称
			// 第二个参数：SQl不允许一个空列，如果ContentValues是空的，那么这一列被明确的指明为NULL值
			// 第三个参数：ContentValues对象
			sqliteDatabase.insert(table, null, values);
			sqliteDatabase.close();
			dbHelper.close();
			// System.out.println("----------insert----------");
		} catch (SQLiteException e) {
			Log.d("e=", e.toString());
		}
	}

	/**
	 * 数据库删除
	 * 
	 * @param context
	 * @param id
	 * @param table
	 */
	public static void delete(Context context, String id, String table) {
		try {
			// 创建DatabaseHelper对象
			DBHelper dbHelper = new DBHelper(context);
			// 获得可写的SQLiteDatabase对象
			SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase();
			// 调用SQLiteDatabase对象的delete方法进行删除操作
			// 第一个参数String：表名
			// 第二个参数String：条件语句
			// 第三个参数String[]：条件值
			sqliteDatabase.delete(table, "id=?", new String[] { id });
			sqliteDatabase.close();
			dbHelper.close();
			// System.out.println("----------delete----------");
		} catch (SQLiteException e) {
			Log.d("e=", e.toString());
		}
	}

	
	/**
	 * 添加单选数据
	 * 
	 * @param 下拉框
	 * @param 字典数据数组
	 * @param 选择内容
	 * @param 是否有默认选项
	 */
	public static void addSpinner(Context context, Spinner spinner,
			String[] strs, String selectStr, Boolean isMoren) {
		ArrayList<String> arraylist = new ArrayList<String>();
		if (isMoren) {
			arraylist.add("");
		}
		for (int i = 0; i < strs.length; i++) {
			arraylist.add(strs[i]);
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
				android.R.layout.simple_spinner_item, arraylist);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		int index = arraylist.indexOf(selectStr);

		if (arraylist.size() > 0 && index != -1) {
			spinner.setSelection(index);
		} else if (index == -1 && arraylist.size() > 0) {
			spinner.setSelection(0);
		}
	}

	/**
	 * 添加单选数据
	 * 
	 * @param context
	 * @param spinner
	 *            下拉框
	 * @param strs
	 *            字典数据数组
	 * @param selectStr
	 *            选择内容
	 */
	public static void addSpinner(Context context, Spinner spinner,
			String[] strs, String selectStr) {
		addSpinner(context, spinner, strs, selectStr, true);
	}

	/**
	 * json转换成Message对象
	 * 
	 * @param json
	 * @return Message
	 */
	public static Message jsonToMessage(String json) {
		Message message = new Message();
		message = (Message) fromJSON(json, Message.class);// 转换成消息盒子
		return message;
	}

	/**
	 * post提交
	 * 
	 * @param url
	 * @param message
	 * @return result
	 */
	public static String postCommit(String url, Message message) {
		String result = "";
		try {
			HTTPCommit commit = new HTTPCommit(url);
			String messageStr = toJSON(message);
			byte[] b = commit.PostCommit(messageStr);
			if (b != null) {
				result = new String(b, "utf-8");
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		return result;
	}
	/**
	 * post提交
	 * @param url 地址
	 * @param message
	 * @param timeout 延迟时间
	 * @return
	 */
	public static String postCommit(String url, Message message,int timeout) {
		String result = "";
		try {
			HTTPCommit commit = new HTTPCommit(url);
			String messageStr = toJSON(message);
			byte[] b = commit.PostCommit(messageStr,timeout);
			if (b != null) {
				result = new String(b, "utf-8");
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		return result;
	}
	/**
	 * 得到消息内容
	 * 
	 * @param message
	 * @return Content
	 */
	public static String getMessageContent(Message message, boolean isEncrypt) {
		String content = message.getMessagebody().getContent();
		if (isEncrypt)// 是否加密
		{
			content = decrypt(content);
		}
		return content;
	}

	/**
	 * 得到消息内容
	 * 
	 * @param message
	 * @return Content
	 */
	public static String getMessageContent(Message message) {
		boolean isEncrypt = message.getMessagehead().getIsEncrypt();// 是否加密
		String content = message.getMessagebody().getContent();
		if (isEncrypt)// 是否加密
		{
			content = decrypt(content);
		}
		return content;
	}

	/**
	 * 安装解压DB文件
	 * 
	 * @param context
	 * @param dbPathString
	 * @param mDBRawResource
	 * @return
	 */
	public static String intallZipDB(Context context, String dbPathString,
			int mDBRawResource) {
		int len = 1024;//

		int readCount = 0, readSum = 0;

		byte[] buffer = new byte[len];

		InputStream inputStream;

		OutputStream output;

		try {

			inputStream = context.getResources()
					.openRawResource(mDBRawResource); // 这里就是Raw文件引用位置

			output = new FileOutputStream(dbPathString);

			ZipInputStream zipInputStream = new ZipInputStream(

			new BufferedInputStream(inputStream));

			ZipEntry zipEntry = zipInputStream.getNextEntry();

			BufferedInputStream b = new BufferedInputStream(

			zipInputStream);

			// StreamLen = (int) zipEntry.getSize();

			while ((readCount = b.read(buffer)) != -1) {

				// readCount = b.read(buffer);

				output.write(buffer, 0, readCount);

				readSum = readSum + readCount;

			}

			output.flush();

			output.close();

		} catch (IOException e) {

			e.printStackTrace();

		}
		return readSum + "";
	}
	/**
	 * 输入框错误提示
	 * @param et	输入框控件
	 * @param text	提示内容
	 */
	public static void editTextError(EditText et,String text)
	{
		et.setError(text);
		et.requestFocus();
	}
	/**
	 * 按钮错误提示
	 * @param btn	按钮控件
	 * @param text	提示内容
	 */
	public static void editTextError(Button btn,String text)
	{
		btn.setError(text);
		btn.requestFocus();
	}
	/**
	 * 日期格式化测试
	 * @param str 日期（yyyy-MM-dd hh:mm:ss）
	 * @param fomcat 日期格式
	 * @return 日期（yyyy-MM-dd）
	 */
	public static String getDateFormat(String str,String fomcat)
	{
//		if(isEmpty(str))
//		{
//			return "";
//		}
		String date="";
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat(fomcat);
		try {
			Date d=simpleDateFormat.parse(str);
			date=(1900+d.getYear())+"-"+(d.getMonth()+1)+"-"+d.getDate();
		} catch (NullPointerException e) {
			//
		}catch (ParseException e) {
			//
		}
		return date;
	}
	/**日期格式化测试
	 * @param str 日期（yyyy-MM-dd hh:mm:ss）
	 * @return 日期（yyyy-MM-dd）
	 */
	public static String getDateFormat(String str)
	{
		String date="";
		if(isEmpty(date))
		{
		    date+=getDateFormat(str,"yyyy-MM-dd");
		}
		if(isEmpty(date))
		{
		    date+=getDateFormat(str,"yyyy-MM-dd hh:mm:ss");
		}
		return date;
	}
	/**
	 * 得到日期的毫秒时间
	 * @param str
	 * @return
	 */
	public static long getDateTime(String str)
	{
		
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date d=simpleDateFormat.parse(str);
			return d.getTime();
		} catch (NullPointerException e) {
			//
		}catch (ParseException e) {
			//
		}
		return -1;
	}
	/**
	 * 设置控件是否可以编辑
	 * @param view 视图
	 * @param isEnabled 是否可以编辑
	 */
	public static void setEnabled(View view,boolean isEnabled)
	{
		view.setEnabled(isEnabled);
		view.setFocusable(isEnabled);
	}
	
	/**
	 * 得到当前时间
	 * @return 时间
	 */
	public static String getCurrentTime() {
		final Calendar c = Calendar.getInstance();
		int mYear = c.get(Calendar.YEAR);
		String mMonth = formatTime(c.get(Calendar.MONTH) + 1);
		String mDay = formatTime(c.get(Calendar.DAY_OF_MONTH));
		String mHear = formatTime(c.get(Calendar.HOUR_OF_DAY));
		String mMinute =formatTime(c.get(Calendar.MINUTE));
		String mSecond = formatTime(c.get(Calendar.SECOND));

		String time = mYear + "-" + mMonth + "-" + mDay + " " + mHear
				+ ":" + mMinute + ":" + mSecond;
		return time;
	}
	/**
	 * 检测是否Http格式
	 * 
	 * @param str
	 * @return
	 */
	public static boolean checkHttp(String str) {
		boolean b = false;
		try {
			Pattern p = Pattern
					.compile("(http://)?([\\w\\d]+[\\.]{1})+[\\w\\d]+([/]?[\\w\\d]+[(\\x21-\\x7e)]?)+");
			Matcher m = p.matcher(str);
			while (m.find()) {
				MatchResult mr = m.toMatchResult();
				//Log.d("intel=", mr.group());
				if (str.length() == mr.group().length()) {
					b = true;
				}
			}
		} catch (IllegalStateException ise) {
			// 没有成功,返回
			b = true;
		} catch (PatternSyntaxException pse) {
			// TODO: handle exception
			// 正则表达式是不正确的
			b = true;
		}
		return b;
	}
	
	/**
	 * 得到联系人,（姓名、电话、email、邮箱）
	 * @param contactUri
	 * @return
	 */
	public static Bundle getContact(Context context,Uri contactUri) {
	      if (contactUri == null) {
	        return null; 
	      }
	      ContentResolver resolver = context.getContentResolver();
	      Cursor contactCursor;
	      try {
	        contactCursor = resolver.query(contactUri, null, null, null, null);
	      } catch (IllegalArgumentException e) {
	        return null;
	      }
	      Bundle bundle =null; 
		if (contactCursor != null && contactCursor.moveToFirst()) {
			bundle = new Bundle();
			int nameColumn = contactCursor
					.getColumnIndex(Contacts.PeopleColumns.NAME);
			if (nameColumn >= 0) {
				String name = contactCursor.getString(nameColumn);
				if (name != null && name.length() > 0) {
					bundle.putString(Contacts.Intents.Insert.NAME,
							massageContactData(name));
				}
			} else {
				// Log.w(TAG, "没有找到? " +
				// Contacts.PeopleColumns.NAME);
			}
			contactCursor.close();

			Uri phonesUri = Uri.withAppendedPath(contactUri,
					Contacts.People.Phones.CONTENT_DIRECTORY);
			Cursor phonesCursor = resolver.query(phonesUri,
					PHONES_PROJECTION, null, null, null);
			if (phonesCursor != null) {
				int foundPhone = 0;
				while (phonesCursor.moveToNext()) {
					String number = phonesCursor
							.getString(PHONES_NUMBER_COLUMN);
					if (foundPhone < Contents.PHONE_KEYS.length) {
						bundle.putString(Contents.PHONE_KEYS[foundPhone],
								massageContactData(number));
						foundPhone++;
					}
				}
				phonesCursor.close();
			}

			Uri methodsUri = Uri.withAppendedPath(contactUri,
					Contacts.People.ContactMethods.CONTENT_DIRECTORY);
			Cursor methodsCursor = resolver.query(methodsUri,
					METHODS_PROJECTION, null, null, null);
			if (methodsCursor != null) {
				int foundEmail = 0;
				boolean foundPostal = false;
				while (methodsCursor.moveToNext()) {
					int kind = methodsCursor.getInt(METHODS_KIND_COLUMN);
					String data = methodsCursor
							.getString(METHODS_DATA_COLUMN);
					switch (kind) {
					case Contacts.KIND_EMAIL:
						if (foundEmail < Contents.EMAIL_KEYS.length) {
							bundle.putString(Contents.EMAIL_KEYS[foundEmail],
									massageContactData(data));
							foundEmail++;
						}
						break;
					case Contacts.KIND_POSTAL:
						if (!foundPostal) {
							bundle.putString(Contacts.Intents.Insert.POSTAL,
									massageContactData(data));
							foundPostal = true;
						}
						break;
					}
				}
				methodsCursor.close();
			}
		}
		return bundle;
	}

	/**
	 * @param data
	 * @return
	 */
	private static String massageContactData(String data) {
		// For now -- make sure we don't put newlines in shared contact data. It
		// messes up
		// any known encoding of contact data. Replace with space.
		if (data.indexOf('\n') >= 0) {
			data = data.replace("\n", " ");
		}
		if (data.indexOf('\r') >= 0) {
			data = data.replace("\r", " ");
		}
		return data;
	}
	/**
	 * 时间转换成数组
	 * @param str
	 * @return
	 */
	public static int[] forTimeNums(String str) {
		String[] date = str.trim().split(":");
		int nums[] = new int[date.length];
		try {

			for (int i = 0; i < date.length; i++) {
				nums[i] = Integer.parseInt(date[i]);
			}
		} catch (Exception e) {

		}
		// Log.d("date-----------", ""+nums[0]+"-"+nums[1]+"-"+nums[2]);
		return nums;
	}
	/**
     * 读取本地图片
     * @return
     */
    public static Intent goLocalImage(Activity activity)
    {
    	DisplayMetrics  dm = new DisplayMetrics(); 
    	activity.getWindowManager().getDefaultDisplay().getMetrics(dm); 
    	int width=200;
    	if(dm.widthPixels<dm.heightPixels)
    	{
    		width=dm.widthPixels;
    	}else
    	{
    		width=dm.heightPixels;
    	}
    	Log.d("width", width+"");
    	Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", width/2);
        intent.putExtra("outputY", width/2);
        intent.putExtra("return-data", true);
        return intent;
        //startActivityForResult(intent, i);
    }
    /**
     * 检测是否到android的市场
     * @param str
     * @return
     */
    public static int checGoMarket(String url) {
		//boolean b = false;
		if(checGoMarket("(market://search\\?q=pname:)", url))
		{
			return ANDROID_MARKET;
		}else if(checGoMarket("(gomarket://details\\?id=)", url))
		{
			return ANZHI_MARKET;
		}else if(checGoMarket("(gfan://fetch\\?p=pid:)", url))
		{
			return GFAN_MARKET;
		}
//		try {
//			Pattern p = Pattern
//					.compile("(market://search\\?q=pname:)");
//			Matcher m = p.matcher(str);
//			while (m.find()) {
//				MatchResult mr = m.toMatchResult();
//				//Log.d("intel=", mr.group());
//				if (str.length() >= mr.group().length()) {
//					b = true;
//				}
//			}
//		} catch (IllegalStateException ise) {
//			// 没有成功,返回
//			//b = true;
//		} catch (PatternSyntaxException pse) {
//			// 正则表达式是不正确的
//			//b = true;
//		}
		return -1;
	}
    
    /**
     * 检测是否到其他的市场
     * @param compile
     * @param url
     * @return
     */
    public static boolean checGoMarket(String compile,String url) {
		boolean b = false;
		try {
			Pattern p = Pattern.compile(compile);
			Matcher m = p.matcher(url);
			while (m.find()) {
				MatchResult mr = m.toMatchResult();
				//Log.d("intel=", mr.group());
				if (url.length() >= mr.group().length()) {
					b = true;
				}
			}
		} catch (IllegalStateException ise) {
			// 没有成功,返回
			//b = true;
		} catch (PatternSyntaxException pse) {
			// 正则表达式是不正确的
			//b = true;
		}
		return b;
	}
    /**
     * 得到url的i码号
   * @param url
   * @return
   */
  public static String checkIcode(String url) {
  		try {
  			Pattern p = Pattern.compile("(code|ewm)=([^\\& ]+)");
  			Matcher m = p.matcher(url);
  			while (m.find()) {
  				MatchResult mr = m.toMatchResult();
  				//Log.d("intel=", mr.group());
  				return mr.group(2);
//  				if (url.length() >= mr.group().length()) {
//  					b = true;
//  				}
  			}
  		} catch (IllegalStateException ise) {
  			// 没有成功,返回
  			//b = true;
  		} catch (PatternSyntaxException pse) {
  			// 正则表达式是不正确的
  			//b = true;
  		}
  		return "";
  	}
	/**
	 * 发送意图
	 * @param context
	 * @param intent
	 */
	public static void launchIntent(Activity activity,Intent intent) {
		if (intent != null) {
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			try {
				activity.startActivity(intent);
			} catch (ActivityNotFoundException e) {
				AlertDialog.Builder builder = new AlertDialog.Builder(activity);
				builder.setTitle(R.string.app_name);
				builder.setMessage(R.string.msg_intent_failed);
				builder.setPositiveButton(R.string.button_ok, null);
				builder.show();
			}
		}
	}
}
